<!-- 捕获规则配置 -->
<template>
  <div class="container">
    <!-- 搜索条件 -->
    <yd-form :options="formOptions" :model="formData" :btns="formBtns"></yd-form>

    <!--查询列表-->
    <YdTable
      :formData="formData"
      :tableConfig="tableConfig"
      :tableData="tableData"
      ref="multipleTable"
      @sizeChangeHandler="searchOriginalDataFilterHandler"
      @currentChangeHandler="searchOriginalDataFilterHandler"
      @sortChangeHandler="searchOriginalDataFilterHandler"
      @selectionChangeHandler="handleSelectionChange"
    >
    </YdTable>

    <!-- 清除数据包对话框 -->
    <el-dialog :title="title" v-model="clearDataOpen"  width="500px" append-to-body
               center>
      <div class="clear-data-radio">
        <el-radio-group v-model="clearDataRadio">
          <el-row>
            <el-radio :label="1">清除所有已捕获数据&emsp;&emsp;&emsp;</el-radio>
          </el-row>
          <el-row>
            <el-radio :label="2">清除三天前所有已捕获数据</el-radio>
          </el-row>
          <el-row>
            <el-radio :label="3">清除七天前所有已捕获数据</el-radio>
          </el-row>
        </el-radio-group>
      </div>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="submitClearDataForm">确 定</el-button>
        <el-button @click="cancelClearDataHandle">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 新增修改对话框 -->
    <el-dialog :title="title" v-model="open"  width="800px" append-to-body center>
      <el-form ref="probeForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-form-item label-width="120px" label="规则名称" prop="ruleName" style="width: 100%">
            <el-input maxlength="50" v-model="form.ruleName"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label-width="120px" label="业务服务资源" prop="resourceCode" style="width: 100%">
            <el-col :span="23">
              <el-input @change="placeholder" @input="change" placeholder="多个服务资源之间以半角逗号隔开"
                        v-model="form.resourceCode"/>
            </el-col>
            <el-col :span="1">
              <svg-icon class-name="orderaddbig" icon-class="orderaddbig" class="orderaddbig-style" @click.stop="resourceCodingClick"/>
            </el-col>
          </el-form-item>
        </el-row>
        <!--请求IP-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="请求IP" label-width="120px" prop="requestiscontain">
              <el-select v-model="form.requestiscontain" @change="$forceUpdate()" clearable placeholder="请选择">
                <el-option
                  v-for="item in options.isContainOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label-width="10px" label="" prop="requestIp">
              <el-input placeholder="多个IP之间以半角逗号隔开" v-model="form.requestIp"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--响应IP-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="响应IP" label-width="120px" prop="responseiscontain">
              <el-select v-model="form.responseiscontain" @change="$forceUpdate()"
                         clearable placeholder="请选择">
                <el-option
                  v-for="item in options.isContainOption"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label-width="10px" label="" prop="responseIp">
              <el-input placeholder="多个IP之间以半角逗号隔开" v-model="form.responseIp"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--时间-->
        <el-row>
          <el-form-item label-width="120px" label="时间" prop="keyword">
            <el-date-picker
              v-model="sTime"
              :disabled-date="disabledDateStart"
              type="datetime"
              @change="sTimeChange"
              v-bind:default-value="defaultValue"
              placeholder="不能小于当前系统时间"
             ></el-date-picker>
                至
             <el-date-picker
              v-model="eTime"
              :disabled-date="disabledDateEnd"
              type="datetime"
              @change="eTimeChange"
              v-bind:default-value="defaultValue"
              placeholder="不能小于开始时间"
             ></el-date-picker>
          </el-form-item>
        </el-row>
        <!--捕获条数-->
        <el-row>
          <el-form-item label-width="120px" label="捕获条数" prop="captureCount" style="width: 50%;">
            <el-input-number :placeholder="form.resourceCode ? '范围0到500' : '范围0到100000'" class="captureCount"
                             v-model="form.captureCount" :min="0" :max="form.resourceCode ? 500 :100000"
                             style="width: 100%;"/>
          </el-form-item>
        </el-row>
        <!--启用状态-->
        <el-row>
          <el-form-item label-width="120px" label="启用状态" prop="switchStatus">
            <el-switch v-model="form.switchStatus"></el-switch> 是否启用该规则
          </el-form-item>
        </el-row>
        <template v-for="(value, index) in keywordConfigForm.formColumn">
          <el-row v-if="index === 0">
            <el-col :span="8">
              <el-form-item label="关键字设置" label-width="120px">
                <el-select v-model="keywordConfigForm.formColumn[index].column" @change="$forceUpdate()" clearable placeholder="请选择">
                  <el-option
                    v-for="item in options.containTypeOption"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label-width="10px" label="">
                <el-input placeholder="请输入要过滤的关键字" v-model="keywordConfigForm.formColumn[index].value"/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <svg-icon v-if="keywordConfigForm.formColumn.length < 5" icon-class="orderadd" class="icon-style" circle @click="addFormRow()"></svg-icon>
            </el-col>
          </el-row>
          <el-row v-if="index > 0">
            <el-col :span="8">
              <el-form-item label="关键字设置" label-width="120px">
                <el-select v-model="keywordConfigForm.formColumn[index].column" @change="$forceUpdate()"
                           clearable placeholder="请选择">
                  <el-option
                    v-for="item in options.containTypeOption"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label-width="10px" label="">
                <el-input placeholder="请输入要过滤的关键字请输入要过滤的关键字" v-model="keywordConfigForm.formColumn[index].value"/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <svg-icon icon-class="orderdel" class="icon-style" circle @click="rmFormRow(index)"></svg-icon>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelHandle">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 添加业务服务资源 -->
    <el-dialog title="添加业务服务资源" v-model="resourceOpen" width="1200px" append-to-body center>
      <el-form :model="queryResourceParams" ref="queryResourceForm" :inline="true">
        <el-form-item label="资源类别" prop="type">
          <el-select v-model="queryResourceParams.type" @change="$forceUpdate()" clearable placeholder="请选择">
            <el-option
              v-for="item in options.categoryOption"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配串类型" prop="identifyType">
          <el-select v-model="queryResourceParams.identifyType" @change="$forceUpdate()" clearable placeholder="请选择">
            <el-option
              v-for="item in options.typeOption"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务资源编码" prop="resourceCode">
          <el-input v-model="queryResourceParams.resourceCode" placeholder="请输入服务资源编码" clearable/>
        </el-form-item>
        <el-form-item label="识别匹配串" prop="identifyStr">
          <el-input v-model="queryResourceParams.identifyStr" placeholder="请输入识别匹配串" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchResourceHandler">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-form ref="resourceFormRef" :model="resourceForm" :rules="rules" :label-width="168">
        <el-row>
          <el-form-item label="选取的业务服务资源编码" prop="showResourceCoding" style="width: 100%">
            <el-input type="textarea" @input="change" v-model="showResourceCoding"/>
          </el-form-item>
        </el-row>

        <!--查询列表-->
        <YdTable
          :formData="queryResourceParams"
          :tableConfig="resourceTableConfig"
          :tableData="tableResourceData"
          ref="multipleTable1"
          @sizeChangeHandler="queryBusinessResourceList"
          @currentChangeHandler="queryBusinessResourceList"
          @sortChangeHandler="queryBusinessResourceList"
          @selectionChangeHandler="handleResourceSelectionChange"
        >
        </YdTable>

      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="submitResourceForm">确 定</el-button>
        <el-button @click="resourceFormCancel">取 消</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="CaptureRulesConfig" lang="tsx">
import {
    getOriginalDataFilter, clearData, getBusinessResourceList, save, getById, updateStatus,
    deleteOriginalDataFilterByIds, sendFilterRule,addOriginalData
} from '@/api/management/packagesAnalysis/captureRulesConfig';
import {parseTime} from '@/utils/common';
import { ref, reactive, toRefs, watch, onMounted, getCurrentInstance } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { useRouter } from 'vue-router';

const { proxy }: any = getCurrentInstance();
const router = useRouter();

// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref("");
const open = ref(false);
//清除数据包弹窗
const clearDataOpen = ref(false);
//资源选择弹窗
const resourceOpen = ref(false);
// 表单参数
const data = reactive<anyObj>({
  form: {}
});
const { form } = toRefs(data);
const formOptions = reactive<FormOptionType>([
  {
    type: 'input',
    label: '捕获规则名称',
    prop: 'ruleName',
    attrs: {
      clearable: true,
    },
  },
]);
const formBtns = reactive<BtnType[]>([
  {
    type: 'primary',
    text: '查询',
    handler: searchOriginalDataFilterHandler,
  },
]);
let resourceForm = ref<anyObj>({
  showResourceCoding: []
});
//下拉框选项
let options = reactive({
  typeOption: [
    {
      key: 1,
      value: 'URL'
    }, {
      key: 2,
      value: 'API'
    }, {
      key: 3,
      value: 'SQL'
    }],
  categoryOption: [
    {
      key: 0,
      value: '非首端业务服务资源'
    }, {
      key: 1,
      value: '关键加载项业务服务资源'
    }, {
      key: 2,
      value: '步骤服务资源'
    }],
  isContainOption: [
    {
      key: 0,
      value: '不包含'
    }, {
      key: 1,
      value: '包含'
    }],
  containTypeOption: [
    {
      key: 0,
      value: '不限'
    }, {
      key: 1,
      value: '请求包体'
    }, {
      key: 2,
      value: '响应包体'
    }]
});
// 表单校验
const rules = ref({
  ruleName: [
    {required: true, message: "规则名称不能为空", trigger: "blur"}
  ],
});
// 搜索表单数据
let formData = reactive<anyObj>({});
let queryResourceParams = reactive<anyObj>({});
//操作完返回信息
let resultData = reactive({});
//行消息提示类型。
const rowMsgType = ref(3);
// 列表配置
let tableConfig = reactive({
  url: getOriginalDataFilter,
  columns: [
    {
      label: '捕获规则名称',
      prop: 'ruleName'
    },
    {
      label: '捕获开始时间',
      prop: 'startTime',
      formatter(row: anyObj, val: ApiVal) {
        return parseTime(val);
      }
    },
    {
      label: '捕获结束时间',
      prop: 'endTime',
      formatter(row: anyObj, val: ApiVal) {
        return parseTime(val);
      }
    },
    {
      label: '捕获条数',
      prop: 'captureCount',
    },
    {
      label: '关键字',
      prop: 'keyword',
      formatter(row: anyObj, val: any) {
        return val? val.replace(/\\/g,'') :'';
      }
    },
    {
      label: '同步实时流',
      prop: 'status',
      formatter(row: anyObj, val: any) {
        const statusOption = ["未同步", "同步中", "同步成功", "同步失败"];
        return statusOption[val];
      }
    },
    {
      label: '同步时间',
      prop: 'syncTime'
    },
    {
      label: '执行结果',
      prop: 'enable',
      formatter(row: anyObj, val: any) {
        const enableOption = ["未执行", "执行中", "执行完成"];
        return enableOption[val];
      }
    },
    {
      label: '已捕获数据',
      prop: 'capturedCount',
      formatter(row: anyObj, val: ApiVal) {
        if (val != null) {
          return val + '条';
        }
      }
    },
    {
      label: '状态',
      prop: 'isEnable',
      render: (row: anyObj, val: ApiVal) => {
        // if (proxy.checkRole(['admin']) || proxy.checkPermi(['metadata:dataFilterConfig:enable'])) {
          return (
            <el-switch v-model={row.isEnable}
                    activeValue={1}
                    inactiveValue={0}
                    onChange={() => isStatusChangeHandle(row)}
            >
            </el-switch>
          )
        // }
        // return (
        //   <el-switch v-model={row.isEnable} disabled activeValue={1} inactiveValue={0}></el-switch>
        // )
      }
    },
    {
      label: '修改人',
      prop: 'creater'
    },
    {
      label: '最后修改时间',
      prop: 'updateTime'
    },
    {
      label: '操作',
      prop: '',
      operation: [
        {
          text: '查看捕获数据',
          handler: (scope: any) => handleSearchOriginals(scope.row)
        }
      ]
    }
  ],
  // 工具栏
  toolBar: [
    {name: '清理数据', icon: 'yd-icon-refresh', permi: ['metadata:dataFilterConfig:refresh'],handler: () => clearHandle()},
    {name: '新增', icon: 'yd-icon-plus', permi: ['metadata:dataFilterConfig:add'],handler: () => handleAdd()},
    {name: '修改', icon: 'yd-icon-edit', permi: ['metadata:dataFilterConfig:edit'],disable: 'single', handler: () => updateHandle()},
    {name: '删除', icon: 'yd-icon-delete',permi: ['metadata:dataFilterConfig:delete'], disable: 'multiple', handler: () => deleteHandle()},
    {
      name: '同步规则',
      icon: 'yd-icon-sync',
      permi: ['metadata:dataFilterConfig:sync'],
      disable: 'multiple',
      handler: () => sendHandle()
    },
  ],
  // 开启复选框
  enableSelection: true,
  // 开启分页
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  // 加载层
  loading: true
});
//业务服务资源表格配置
let resourceTableConfig = reactive({
  url: getBusinessResourceList,
  columns: [
    {
      label: '资源类型',
      prop: 'type',
      formatter(row: anyObj, val: string) {
        const categoryOptions = ['非首端服务资源', '关键加载项服务资源', '步骤服务资源'];
        return categoryOptions[val];
      }
    },
    {
      label: '匹配串类型',
      prop: 'identifyType',
      formatter(row: anyObj, val: string) {
        const typeOptions = ["", "URL", "API", "SQL"];
        return typeOptions[val];
      }
    },
    {
      label: '业务服务资源编码',
      prop: 'resourceCode'
    },
    {
      label: '识别匹配串',
      prop: 'identifyStr',
      showOverFlowToolTip: true,
    }
  ],
  // 工具栏
  toolBar: [],
  // 开启复选框
  enableSelection: true,
  // 开启分页
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  // 加载层
  loading: true
});
// 列表数据
let tableData = ref([]);
// 列表数据
let tableResourceData = ref([]);
const showResourceCoding = ref<any>();
//关键字设置表单
let keywordConfigForm = reactive({
  formColumn: [{column: '', value: ''}],
});
const gridRow = ref([]);
const clearDataRadio = ref(0);
let resourceCodings = [];
let selectObjects = [];
const isClick = ref(false); // 判断调用handleResourceSelectionChange方法时是不是由于点击弹窗按钮所引起的
const dateRange = ref([]);
const sTime = ref('');
const eTime = ref('');
const captureCountPlaceholder = ref('范围0到100000');
const captureCountMax = ref(100000);
const defaultEndTime = ref("");
const defaultValue = ref(new Date());
// 禁选日期
const disabledDateStart = (time: any) => {
  return time.getTime() <= Date.now() - 24 * 3600 * 1000;
}
const disabledDateEnd = (time: any) => {
  return time.getTime() <= Date.now()- 24 * 3600 * 1000;
}
const multipleTable1 = ref<any>();
const probeForm = ref<any>();
const resourceFormRef = ref<any>();

watch(showResourceCoding, (newVal, oldVal) => {
  if (newVal !== '') {
    selectObjects = newVal.split(',');
  }else {
    selectObjects = [];
  }
});
watch(sTime, (newVal, oldVal) => {
  if (eTime.value != '' && newVal > eTime.value ) {
    eTime.value = '';
  }
});
onMounted(() => {
  searchOriginalDataFilterHandler();
});

function getDefaultValue() {
  defaultValue.value = new Date();
}
function sTimeChange() {
  let startAt = new Date(sTime.value).getTime() * 1000 / 1000;
  if (startAt < Date.now()) {
    sTime.value = parseTime(new Date().getTime());
  }
}
function eTimeChange() {
  let endT = new Date(eTime.value).getTime() * 1000 / 1000;
  let startT = new Date(sTime.value).getTime() * 1000 / 1000;
  if(endT < startT ) {
    eTime.value = sTime.value;
  }
  if (endT <  Date.now()) {
    eTime.value = parseTime(new Date().getTime());
  }
}
/*搜索*/
function searchOriginalDataFilterHandler() {
  tableConfig.pagination.pageNum = 1;
  queryOriginalDataFilter();
}
function searchResourceHandler() {
  queryResourceParams.pageNum = 1;
  queryBusinessResourceList();
}
/*查询探针数据过滤信息*/
function queryOriginalDataFilter() {
  tableConfig.loading = true;
  getOriginalDataFilter(formData).then((res: ApiResponse) => {
    tableData.value = res.data.records;
    tableConfig.pagination.total = res.data.total;
    tableConfig.loading = false;
  });
}
/*查询业务服务资源信息*/
function queryBusinessResourceList() {
  resourceTableConfig.loading = true;
  getBusinessResourceList(queryResourceParams).then((res: ApiResponse) => {
    tableResourceData.value = res.data.records;
    resourceTableConfig.pagination.total = res.data.total;
    resourceTableConfig.loading = false;
  });
}
function clearHandle() {
  reset();
  title.value = "清除数据包";
  clearDataOpen.value = true;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  defaultValue.value = new Date(),
  sTime.value = '';
  eTime.value = '';
  getDefaultValue();
  title.value = "新增原始数据包捕获规则";
  form.value.resourceCode = '';
  open.value = true;
}
function getIpRow(data: string) {
  let column, value;
  if (data != null && data !== '') {
    if (data.indexOf('prep') === 0) {
      column = 0;
      value = data.replace('prep\\:', '');
    } else {
      column = 1;
      value = data.replace('in\\:', '');
    }
    value = value.replace(/\\/g,'');
  }
  return {column: column, value: value};
}
/** 修改按钮操作 */
function updateHandle() {
  reset();
  title.value = "编辑原始数据包捕获规则";
  const id = ids.value;
  form.value.resourceCode = '';
  getById(id).then((response: ApiResponse) => {
    const is = [false, true];
    form.value = response.data[0];
    form.value.switchStatus = is[form.value.isStatus];
    if (form.value.startTime !== null && form.value.startTime != '') {
      // dateRange = [form.value.startTime, form.value.endTime];
      sTime.value = form.value.startTime;
      eTime.value = form.value.endTime;
    }
    if(form.value.captureCount === null) {
      form.value.captureCount = undefined;
    }
    let requestRow = getIpRow(form.value.requestIp);
    form.value.requestiscontain = requestRow.column;
    form.value.requestIp = requestRow.value;
    let responseRow = getIpRow(form.value.responseIp);
    form.value.responseiscontain = responseRow.column;
    form.value.responseIp = responseRow.value;
    if (form.value.keyword != null && form.value.keyword !== '') {
      let rows: any = [];
      let keywords = form.value.keyword.split(',');
      keywords.forEach((row: string) => {
        let column, value;
        if (row.indexOf('A') === 0) {
          value = row.replace('A\\:', '');
          column = 0
        }
        if (row.indexOf('Q') === 0) {
          value = row.replace('Q\\:', '');
          column = 1
        }
        if (row.indexOf('P') === 0) {
          value = row.replace('P\\:', '');
          column = 2
        }
        rows.push({column: column, value: value?.replace('\\', '')})
      });
      keywordConfigForm.formColumn = rows;
    }
    open.value = true;
  });
}
/** 删除按钮操作 */
function deleteHandle() {
  proxy.$modal.confirm('确定删除吗?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    cancelButtonClass: 'confirm-rigth-cancel-button',
    type: "warning"
  }).then(() => {
    deleteOriginalDataFilterByIds(ids.value).then((res: ApiResponse) => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess("删除成功");
          searchOriginalDataFilterHandler();
      } else {
        proxy.$modal.msgWarning(res.msg);
      }
    });
  }).catch(() => {});
}
// 发送规则
function sendHandle() {
  const rows: any = gridRow.value;
  if (rows.length <= 10) {
    let msg = '是否同步?';
    for (let j = 0; j < rows.length; j++) {
      let enable = rows[j].enable;
      let status = rows[j].status;
      if ((status === 2 || status === 0) && enable === 2) {
        msg = '是否同步？发送后将清除对应规则已捕获的数据';
      }
      proxy.$modal.confirm(msg, "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        cancelButtonClass: 'confirm-rigth-cancel-button',
        type: "warning"
      }).then(() => {
        sendFilterRule({ids: ids.value}).then((res: ApiResponse) => {
          if (res.code === 0) {
            proxy.$modal.msgSuccess("发送成功");
            queryOriginalDataFilter();
          } else {
            proxy.$modal.msgSuccess(res.msg);
          }
        });
      }).catch(() => {});
    }
  } else {
    proxy.$modal.alert('最多只能发送十条规则!', '提示', {
      confirmButtonText: "确定",
      type: "info"
    });
  }
}
/**多选框选中数据*/
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: anyObj) => item.id);
  gridRow.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
/**服务资源列表多选框选中数据*/
function handleResourceSelectionChange(selection: any) {
  proxy.$forceUpdate();
  resourceCodings = selection.map((item: anyObj) => item.resourceCode);
  showResourceCoding.value = resourceCodings.join(',');
}
/** 提交按钮 */
function submitForm() {
  probeForm.value.validate((valid: any) => {
    if (valid) {
      const request = ['prep\\:' + form.value.requestIp, 'in\\:' + form.value.requestIp];
      const response = ['prep\\:' + form.value.responseIp, 'in\\:' + form.value.responseIp];
      let params: anyObj = {};
      Object.assign(params, form.value);
      proxy.addDateRange(params, dateRange.value);
      //请求ip
      params.requestIp = request[form.value.requestiscontain];
      //响应ip
      params.responseIp = response[form.value.responseiscontain];
      let keywords: any = [];
      keywordConfigForm.formColumn.forEach((row: anyObj) => {
        if (row.value.indexOf(",") !== -1) {
          proxy.$modal.msgError("关键字不能包含特殊字符");
          return false;
        }
        let as = getKeywordIsContain(row.column, row.value);
        if (as !== '') keywords.push(as);
      });
      //最终返回后台的关键字
      params.keyword = keywords.join(',');
      if (sTime.value == '' && eTime.value == '' && form.value.captureCount === undefined) {
        proxy.$modal.msgError("时间和捕获条数必须选择一项");
        return false;
      }
      if ((!sTime.value || !eTime.value) && form.value.captureCount === undefined) {
        proxy.$modal.msgError("请选择对应的开始时间或结束时间");
        return false;
      }
      params.isStatus = isStatusClick(form.value.switchStatus);
      params.startTime = parseTime(sTime.value);
      params.endTime = parseTime(eTime.value);
      params.switchStatus = undefined;
      if(title.value === '新增原始数据包捕获规则'){
        addOriginalData(params).then((response: ApiResponse) => {
          console.log('?');
          if (response.code === 0) {
            tableData.value = []
            searchOriginalDataFilterHandler();
            open.value = false;
            if (params.id > 0) {
              proxy.$modal.msgSuccess("编辑成功,捕获数据将在同步成功后删除");
            } else {
              proxy.$modal.msgSuccess("保存成功");
            }
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        save(params).then((response: ApiResponse) => {
          console.log('?');
          if (response.code === 0) {
            tableData.value = []
            searchOriginalDataFilterHandler();
            open.value = false;
            if (params.id > 0) {
              proxy.$modal.msgSuccess("编辑成功,捕获数据将在同步成功后删除");
            } else {
              proxy.$modal.msgSuccess("保存成功");
            }
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
      
    }
  });
}
/** 清理数据提交按钮 */
function submitClearDataForm() {
  if (clearDataRadio.value === 0) {
    proxy.$modal.msg("请选择清理条件");
  } else {
    proxy.$modal.confirm('确定清除吗?', "确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      cancelButtonClass: 'confirm-rigth-cancel-button',
      type: "warning"
    }).then(() => {
      clearData(clearDataRadio.value).then((res: ApiResponse) => {
        if (res.code === 0) {
          proxy.$modal.msgSuccess("清理成功");
          cancelClearDataHandle();
          queryOriginalDataFilter();
        }
      });
    }).catch(() => {});
  }
}
/**
 * 资源选择弹窗确认
 */
function submitResourceForm() {
  resourceFormRef.value.validate((valid: any) => {
    if (resourceCodings.length > 10) {
      proxy.$modal.msgError("最多只能选择十条业务服务资源");
      return null;
    }
    if (valid) {
      form.value.resourceCode = showResourceCoding.value;
      placeholder();
      resourceOpen.value = false;
    }
  });
}
/**
 * 资源选择弹窗取消
 */
function resourceFormCancel() {
  resourceOpen.value = false;
}
/*取消*/
function cancelHandle() {
  open.value = false;
  proxy.$forceUpdate();
}
/*清除数据包取消*/
function cancelClearDataHandle() {
  clearDataOpen.value = false;
}
/*重置表单*/
function reset() {
  dateRange.value = [];
  clearDataRadio.value = 0;
  resourceCodings = [];
  selectObjects = [];
  form.value = {};
  sTime.value = '';
  eTime.value = '';
  defaultValue.value = new Date();
  defaultEndTime.value = '';
  resourceForm.value = {};
  keywordConfigForm.formColumn = [{column: '', value: ''}];
  probeForm.value?.resetFields();
  resourceFormRef.value?.resetFields();
}
//下拉框改变
function changeHandle() {
  proxy.$forceUpdate();
}
// 禁用启用
function isStatusChangeHandle(row: anyObj) {
  let message = "确定启用吗?";
  if (row.isEnable === 0) {
    message = "确定禁用吗?";
  }
  proxy.$modal.confirm(message, "确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    cancelButtonClass: 'confirm-rigth-cancel-button',
    type: "warning"
  }).then(() => {
    updateStatus({ids: [row.id], isEnable: row.isEnable }).then((res: ApiResponse) => {
      if (res.code === 0) {
        proxy.$modal.msgSuccess("更新状态成功");
        queryOriginalDataFilter();
      } else {
        proxy.$modal.msgError(res.msg);
        row.isEnable = row.isEnable === 1 ? 0 : 1
      }
    });
  }).catch(() => {
    row.isEnable = row.isEnable === 1 ? 0 : 1
  })
}
/*查看捕获数据*/
function handleSearchOriginals(row: anyObj) {
  router.push({
    path: '/management/packagesAnalysis/originalPacketDisplay',
    query: {
      filterId: row.id,
    }
  })
}
//业务服务资源选择弹窗按钮触发
function resourceCodingClick() {
  // 再次进入该窗口先清空上一次的搜索条件
  if(!(queryResourceParams.type == null)) { queryResourceParams.type=''; }
  if(!(queryResourceParams.identifyType == null)) { queryResourceParams.identifyType=''; }
  if(!(queryResourceParams.resourceCode == null)) { queryResourceParams.resourceCode=''; }
  if(!(queryResourceParams.identifyStr == null)) { queryResourceParams.identifyStr=''; }
  isClick.value = true;
  searchResourceHandler();
  if(form.value.resourceCode) {
    // 进行回显
    showResourceCoding.value = form.value.resourceCode;
    selectObjects = showResourceCoding.value.split(',');
  }
  resourceOpen.value = true;
}
function resultChange() {
  if (showResourceCoding.value != null) {
    selectObjects = showResourceCoding.value.split(',');
  }else {
    selectObjects = [];
  }
}
// 复选框回显
function toggleSelectionBack(rows: any) {
  if(rows) {
    rows.forEach((row: anyObj) => {
      proxy.$nextTick(() => {
        multipleTable1.value.getTableRef().toggleRowSelection(row, true);
      })
    })
  }
}
/*动态自定义提示信息*/
function placeholder() {
  if (form.value.resourceCode) {
    if (form.value.resourceCode.trim() === '') {
      captureCountMax.value = 100000;
      return captureCountPlaceholder.value = '范围0到100000';
    } else {
      captureCountMax.value = 500;
      if (form.value.captureCount > 500) {
        form.value.captureCount = 500;
      }
      return captureCountPlaceholder.value = '范围0到500';
    }
  }
  captureCountMax.value = 100000;
  return captureCountPlaceholder.value = '范围0到100000';
}
/*刷新*/
function change() {
  proxy.$forceUpdate();
}
/*状态切换*/
function isStatusClick(value: any) {
  if (value) {
    return 1;
  }
  return 0;
}
/**
* 删除form行
* @param index 下标
*/
function rmFormRow(index: number) {
  keywordConfigForm.formColumn.splice(index, 1);
}
/**
* 添加form行
*/
function addFormRow() {
  const lastitem: any = keywordConfigForm.formColumn[keywordConfigForm.formColumn.length - 1];
  if (lastitem === '' || lastitem.column === '' || lastitem.value.trim() === '') {
    proxy.$modal.msgError('请您填写完一项后继续追加')
  } else {
    keywordConfigForm.formColumn.push({column: '', value: ''})
  }
}
//获取关键字,拼接 A:不限 Q:请求包体 P:响应包体
function getKeywordIsContain(isContain: number, keyword: any) {
  if (isContain === 0 && keyword !== '') {
    return 'A:' + keyword;
  }
  if (isContain === 1 && keyword !== '') {
    return 'Q:' + keyword;
  }
  if (isContain === 2 && keyword !== '') {
    return 'P:' + keyword;
  }
  return '';
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .container {
    margin: 10px;
  }

  .clear-data-radio {
    :deep .el-radio-group {
      line-height: 3;
      font-size: 16px;
    }

    :deep .el-radio__label {
      font-size: 16px;
    }
  }

  .icon-style {
    vertical-align: middle;
    font-size: 22px;
    margin-left: 15px;;
    height: 35px;
  }

  .orderaddbig-style {
    vertical-align: middle;
    margin-left: 5px;
    font-size: 22px;
    cursor: pointer;
  }
</style>
<style rel="stylesheet/scss" lang="scss">
.captureCount{
  .el-input-number__decrease, .el-input-number__increase{
      background-color: #0097a7!important;
      border-color: #0097a7!important;
    }
}
</style>
